#include <sys/types.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>

// 获取该文件夹的大小
int get_dir_size(const char* tar_dir_path) {
	DIR* root = opendir(tar_dir_path);
	if (root == NULL) {
		printf("不存在这样的文件夹: %s\n", tar_dir_path);
		return -1;
	}
	struct dirent *dir_entry = NULL;
	int total_size = 0;
	while (dir_entry = readdir(root)) {
		char entry_path[256] = {0};
		sprintf(entry_path, "%s/%s", tar_dir_path, dir_entry->d_name);
		printf("current file: %s\n", entry_path);

		// if this entry is regular file
		if (dir_entry->d_type == DT_REG) {
			struct stat file_info;
			stat(entry_path, &file_info);
			total_size += file_info.st_size;
		}
		// else if this entry is a dir
		else if (dir_entry->d_type == DT_DIR) {
			if (strcmp(dir_entry->d_name, ".") == 0 || strcmp(dir_entry->d_name, "..") == 0) {
				continue;
			}

			total_size += get_dir_size(entry_path);
		}
	}
	closedir(root);

	return total_size;
}

int main(int argc, char* argv[]) {
	if (argc != 2) {
		printf("执行格式错误，示例：./exe filename\n");
	}

	char* tar_dir_path = argv[1];
	if (tar_dir_path[strlen(tar_dir_path) - 1] == '/' ) {
		tar_dir_path[strlen(tar_dir_path) - 1] = '\0';
	}

	printf("目标文件夹：%s\n", tar_dir_path);
	int size = get_dir_size(tar_dir_path);
	printf("目标文件夹的大小为：%d\n", size);
	return 0;
}
